package demo.socket.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 * @author daify
 * @date 2019-08-23 11:35
 **/
public class SocketServer {

    public static void main(String[] args) throws IOException {
        echoesSocketServer();
    }
    
    /**
     * 回声服务器
     */
    public static void echoesSocketServer() throws IOException {
        
        try (ServerSocket server = new ServerSocket(8000);
             // 服务端在调用accept（）等待客户端的连接请求时会阻塞，直到收到客户端发送的连接请求才会继续往下执行代码
             Socket client = server.accept();
             // 获取Socket的输出流，用来向客户端发送数据
             OutputStream outputStream = client.getOutputStream();
             // 获取Socket的输入流，用来获得客户端的数据
             InputStream inputStream = client.getInputStream()){
            
            // 解析收到的消息
            String message = getMessage(inputStream);
            System.out.println("get message from client: " + message);
            // 添加echo后重新返回消息
            outputStream.write(("echo:" + message).getBytes());
            // 关闭此次输出流
            client.shutdownOutput();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 基础是Socket案例
     */
    public static void baseSocketServer() {
        int port = 8000;
        try (ServerSocket socket = new ServerSocket(port);
             // server将一直等待连接的到来
             Socket accept = socket.accept();
             // 获取Socket的输入流，用来获得客户端的数据
             InputStream inputStream = accept.getInputStream()) {
            // 解析收到的消息
            String message = getMessage(inputStream);
            System.out.println("get message from client: " + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对输入流进行解析获得返回的内容
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static String getMessage(InputStream inputStream) throws IOException {
        // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
            sb.append(new String(bytes, 0, len,"UTF-8"));
        }
        return sb.toString();
    }
}
